import  React,{ useEffect, useState } from 'react';
import {
  Form,
  Row,
  Col,
  Space,
  Button,
  Upload,
  Input,
  message
} from 'antd';
import { connect, useModel,history } from 'umi';
import { useLocation } from 'react-router'
import {
  FormSelect,
  FormInput,
  FormTime,
} from '@/components/SearchForm/SearchFormItem';
import { uploadFileUrl } from '@/service/common/upload';
import cardStyles from '../index.less';
import { orderChangeCar } from '@/service/order';
import { formatDate } from '@/utils/common/dateFilter';
import { getAllParking } from '@/service/storage/archives';
import SelectCar from '../common/selectCar';
import {getUseList} from '@/service/system/user'
import {  getCookie } from '@/utils/cookie';

const formLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 12, offset: 0 },
  },
};
const styles = { width300: { width: '300px' }, width600: { width: '600px' } };
function ExchangeCar(props: any) {
  const {infos} = props;
  // const dispatch = useDispatch();
  const { initialState } = useModel('@@initialState');
  const { fileName } = initialState || {};
  const [form] = Form.useForm();
  const [allParking, setAllParking] = useState<any>([]);
  const [oldFileList, setOldFileList] = useState<any>([]); // 原车上传验车清单
  const [newFileList, setNewFileList] = useState<any>([]); // 新车上传验车清单
  const [contractFileList, setContractFileList] = useState<any>([]); // 合同上传验车清单
  const [newEnclosureFileList, setNewEnclosureFileList] = useState<any>([]); // 合同上传验车清单
  const [carId ,setCarId] = useState() // 车辆ID
  const [loading, setLoading] = useState(false)
  /** 获取请车厂列表 */
  const allParkingFun = () => {
    getAllParking({  }).then((res: any) => {
      if (res?.data) {
        setAllParking(() => res.data);
      }
    });
  };
  useEffect(() => {
    allParkingFun();
  }, []);
  const [orderIds,setOrderIds] = useState('')
    // 获取路由中订单编号
  const location = useLocation()
  const routerName = () => {
      setOrderIds(location?.search?.split('id=')[1])
  }
  useEffect(() => {
    routerName();
  }, []);
 //  文件上传生成上传信息-上传原车验车清单
 const uploadPropsOld = {
  action: uploadFileUrl,
  name: fileName, // 滴滴上传:file 测试上传:files
  data: {
    modelName: 'carOrder',
    targetAttr: 2,
  },
  beforeUpload: (file: any) => {
    const isLt200M = file.size / 1024 / 1024 < 200
    if (!isLt200M) {
      message.error('文件必须小于200MB')
    }
    return isLt200M
  },
  onChange(info: any) {
    if (info.file.status === 'done') {
      setOldFileList(info?.fileList);
      const list:any = []
      info?.fileList?.map((res:any)=>list.push(res?.response?.data.id))
      form.setFieldsValue({oldAttachmentList:list});
    }
    setOldFileList(info?.fileList);
  },
  onRemove(info: any) {
    form.setFieldValue('oldAttachmentList','');
    message.success(`${info?.name}移除成功`)
  },
  oldFileList,
};
 //  文件上传生成上传信息-新车
 const uploadPropNew = {
  action: uploadFileUrl,
  name: fileName, // 滴滴上传:file 测试上传:files
  data: {
    modelName: 'carOrder',
    targetAttr: 3,
  },
  beforeUpload: (file: any) => {
    const isLt200M = file.size / 1024 / 1024 < 200
    if (!isLt200M) {
      message.error('文件必须小于200MB')
    }
    return isLt200M
  },
  onChange(info: any) {
    if (info.file.status === 'done') {
      setContractFileList(info?.fileList);
      const list:any = []
      info?.fileList?.map((res:any)=>list.push(res?.response?.data.id))
      form.setFieldsValue({contractAttachmentList:list});
    }
    setContractFileList(info?.fileList);
  },
  onRemove(info: any) {
    form.setFieldValue('contractAttachmentList','');
    message.success(`${info?.name}移除成功`)
  },
  contractFileList,
};
//  文件上传生成上传信息-合同
const uploadPropContract = {
  action: uploadFileUrl,
  name: fileName, // 滴滴上传:file 测试上传:files
  data: {
    modelName: 'carOrder',
    targetAttr: 3,
  },
  beforeUpload: (file: any) => {
    const isLt200M = file.size / 1024 / 1024 < 200
    if (!isLt200M) {
      message.error('文件必须小于200MB')
    }
    return isLt200M
  },
  onChange(info: any) {
    if (info.file.status === 'done') {
      setNewFileList(info?.fileList);
      const list:any = []
      info?.fileList?.map((res:any)=>list.push(res?.response?.data.id))
      form.setFieldsValue({uoloadAttachmentList:list});
    }
    setNewFileList(info?.fileList);
  },
  onRemove(info: any) {
    form.setFieldValue('uoloadAttachmentList','');
    message.success(`${info?.name}移除成功`)
  },
  newFileList,
};
//  文件上传生成上传信息-交车附件
const uploadPropNewEnclosure = {
  action: uploadFileUrl,
  name: fileName, // 滴滴上传:file 测试上传:files
  data: {
    modelName: 'carOrder',
    targetAttr: 3,
  },
  beforeUpload: (file: any) => {
    const isLt200M = file.size / 1024 / 1024 < 200
    if (!isLt200M) {
      message.error('文件必须小于200MB')
    }
    return isLt200M
  },
  onChange(info: any) {
    if (info.file.status === 'done') {
      setNewEnclosureFileList(info?.fileList);
      const list:any = []
      info?.fileList?.map((res:any)=>list.push(res?.response?.data.id))
      form.setFieldsValue({closureAttachmentList:list});
    }
    setNewEnclosureFileList(info?.fileList);
  },
  onRemove(info: any) {
    form.setFieldValue('closureAttachmentList','');
    message.success(`${info?.name}移除成功`)
  },
  newEnclosureFileList,
};

// const onCancel = () => {
//   dispatch({
//     type: 'global/deleteTabs',
//     payload: currentRoute,
//   });
//   history.goBack();
// };
const [openModal, setOpenModal] = useState(false);
// 选择获取车辆信息
const handleSerach  = (value:any)=>{
  
  const info1 = {...value}
  setCarId(info1.carId)
  switch (info1.insuranceType){
    case -1 : info1.insuranceType = ''
     break
    case 1 : info1.insuranceType = '交强险'
      break
    case 2 : info1.insuranceType = '商业险'
      break
    case 3 : info1.insuranceType = '承运险'
     break
    case 4 : info1.insuranceType = '交强险/商业险'
     break
    case 5 : info1.insuranceType = '交强险/承运险'
     break
    case 6 : info1.insuranceType = '商业险/承运险'
     break
    case 7 : info1.insuranceType = '交强险/商业险/承运险'
     break
     default:
  }
    form.setFieldsValue(info1)
    setOpenModal(false)
}
const [workerList,setWorkerList] = useState<any>([]); // 工作人员列表
  // cookies中获取公司id
const merchantIds: any = getCookie('orgId');
  useEffect(()=>{
    getUseList({merchantId:merchantIds}).then((res:any)=>{
        setWorkerList(res?.data)
    })
  },[merchantIds])
// 提交
const onFinish = async () => {
  setLoading(true)
  const params: any = {};
  try {
    const values = await form.validateFields();
    params.quondamOrderCarId = orderIds;
    params.applyTime = formatDate(values?.applyTime, 'YYYY-MM-DD HH:mm:ss'); // 换车时间
    params.applyRemark = values?.applyRemark;
    params.putDepotId = Number(values?.putDepotId); // 退回仓库ID
    allParking?.forEach((res:any)=>{
        if(res.id === values?.putDepotId){
           params.putDepotName = res?.warehouseName // 退回仓库名称
        }
    })
    // 绑车
    params.tiedCar = {
      carId, // 车辆ID
      vinNo: values?.vin, // 车架号
      plateNo: values?.number || '123343', // 车牌号
      brandName: values?.carFullName, // 车辆品系
      cityName: values?.cityName, // 车辆城市
      depotName: values?.warehouseName, // 车辆仓库 
      insuranceNames: values?.insuranceType,// 已经购买险种
      tiedRemark: values?.tiedRemark, // 绑车备注
    };
    // 还车-验车
    params.validateReturnCar = {
      validatePerson: values?.validateReturnCarPerson, // 验车人
      validateTime:  formatDate(values?.validateReturnCarTime, 'YYYY-MM-DD HH:mm:ss'), // 还车时间
      validateType: 2, // 验车类型
      remark: values?.ReturnCarRemark, // 验车备注
      attachmentList: values?.oldAttachmentList, // 上传验车清单附件
    };
    // 交车
    params.validateDeliveryCar = {
      validatePerson: values?.validatePerson, // 验车人
      validateTime:  formatDate(values?.validateTime, 'YYYY-MM-DD HH:mm:ss'), // 还车时间
      validateType: 1, // 验车类型
      remark: values?.remark, // 验车备注
      attachmentList: values?.contractAttachmentList, // 上传验车清单附件
    };
     // 合同
     params.signedData = {
      remark: values?.contractRemark, // 合同备注
      attachmentList: values?.uoloadAttachmentList, // 合同附件
    };
    // 交车
    workerList?.forEach((res:any)=>{
      if(res.id === values?.deliveryPerson){
         values.deliveryPersonName = res.name
      }
    })
    params.deliveryData = {
      deliveryPersonId: values?.deliveryPerson, // 交车人ID
      deliveryPerson: values?.deliveryPersonName, // 交车人姓名
      remark: values?.newRemark, // 备注
      deliveryTime:formatDate(values?.deliveryTime, 'YYYY-MM-DD HH:mm:ss'), // 交车时间
      attachmentList: values?.closureAttachmentList, // 交车附件
    };
    orderChangeCar(params).then((res:any) => {
      if (res.success) {
        setLoading(false)
        history.goBack()
      }
      });
    } catch (error) { /* empty */ }
    
  }
  // 取消
  const  chanle = ()=>{
    history.goBack();
  }
  return (
    <div className={cardStyles.card} id="exchangeCar">
      <Form
        form={form}
        onFinish={onFinish}
        {...formLayout}
        wrapperCol={{ flex: 1 }}
        autoComplete="off"
      >
        <p className={cardStyles.title}>换车申请</p>
        <Row gutter={24} className={cardStyles.rows}>
          <Col span={24}>
            <FormTime
              name="applyTime"
              subtype="date"
              label="换车时间"
              style={styles.width300}
              rules={[{ required: true, message: '请选择换车时间' }]}
            />
          </Col>
          <Col span={24}>
            <FormInput
              name="applyRemark"
              label="换车原因"
              placeholder="请填写换车原因，不超过200个字符"
              style={styles.width600}
              rules={[{ required: true, message: '请填写换车原因' }]}
            />
          </Col>
          <Col span={24}>
            <FormSelect
              style={styles.width300}
              name="putDepotId"
              label="退回仓库"
              placeholder="请选择退回仓库"
              rules={[{ required: true, message: '请选择退回仓库' }]}
              items={allParking}
              keys='id'
              title='warehouseName'
            />
          </Col>
        </Row>

        <p className={cardStyles.title}>绑定新车辆</p>
        <Row gutter={24} className={cardStyles.rows}>
          <Col span={24}>
            <Form.Item
                  name="vin"
                  label="选择车架号"
                  rules={[{ required: true, message: '请选择车架号!' }]}
                >
                  <Input
                    placeholder="请选择车架号"
                    onClick={() => setOpenModal(true)}
                    style={{ width: '300px' }}
                  />
              </Form.Item>
          </Col>
          <Col span={24}>
            <FormInput
              name="number"
              label="选择车牌号"
              rules={[{ required: true, message: '请选择车牌号!' }]}
              placeholder="选择车牌号后自动带出"
              style={styles.width300}
              disabled
            />
          </Col>
          <Col span={24}>
            <FormInput
              name="carFullName"
              label="车型品牌/车系"
              placeholder="选择车牌号/车架号自动获取"
              style={styles.width300}
              disabled
            />
          </Col>
          <Col span={24}>
            <FormInput
              name="cityName"
              label="车辆所在城市"
              placeholder="选择车辆所在城市自动获取"
              style={styles.width300}
              disabled
            />
          </Col>
          <Col span={24}>
            <FormInput
              name="warehouseName"
              label="车辆所在仓库"
              placeholder="选择车牌号/车架号自动获取"
              style={styles.width300}
              disabled
            />
          </Col>
          <Col span={24}>
            <Form.Item name="insuranceType" label="车辆已购保险">
                <Input
                      disabled
                      placeholder="车辆已购保险"
                  style={{ width: '300px' }}
                />
            </Form.Item>
          </Col>
          <Col span={24}>
            <FormInput
              name="tiedRemark"
              label="备注"
              maxLength={200}
              placeholder="请填写绑车备注信息，不超过200个字符"
              allowClear
              style={styles.width600}
            />
          </Col>
        </Row>
        {/* 选择车辆弹框 */}
        {infos &&
             <SelectCar
          title="选择绑定车辆"
          setIsOpen={setOpenModal}
          isOpen={openModal}
          handleSerach={handleSerach}
          brandId={infos}
        />
        }
       
        <p className={cardStyles.title}>原车验车信息</p>
        <Row gutter={24} className={cardStyles.rows}>
          <Col span={24}>
            <FormInput
              name="validateReturnCarPerson"
              label="验车人员"
              rules={[{ required: true, message: '请填写验车人员' }]}
              placeholder="请填写验车人员"
              allowClear
              style={styles.width300}
            />
          </Col>
          <Col span={24}>
            <FormTime
              subtype="date"
              name="validateReturnCarTime"
              label="验车时间"
              rules={[{ required: true, message: '请选择验车时间' }]}
              placeholder="请填写验车时间"
              allowClear
              style={styles.width300}
            />
          </Col>
          <Col span={24}>
            <FormInput
              name="ReturnCarRemark"
              label="备注"
              maxLength={200}
              placeholder="请填写绑车备注信息，不超过200个字符"
              allowClear
              style={styles.width600}
            />
          </Col>
          <Col span={24}>
            <Form.Item
              label="验车清单上传"
              name="oldAttachmentList"
              rules={[{ required: true, message: '请上传验车清单' }]}
            >
              <Upload {...uploadPropsOld}>
                    {oldFileList?.length >= 5 ? null : <Button>添加清单</Button>}
                </Upload>
              <p style={{ margin: '15px 0 0 0' }}>
                清单说明：附件最大支持200M，
              </p>
              <p>支持格式：PDF、Word、Excel、JPG、PNG</p>
            </Form.Item>
          </Col>
        </Row>
        <p className={cardStyles.title}>新车验车信息</p>
        <Row gutter={24} className={cardStyles.rows}>
          <Col span={24}>
            <FormInput
              name="validatePerson"
              label="验车人员"
              rules={[{ required: true, message: '请填写验车人员' }]}
              placeholder="请填写验车人员"
              allowClear
              style={styles.width300}
            />
          </Col>
          <Col span={24}>
            <FormTime
              subtype="date"
              name="validateTime"
              label="验车时间"
              rules={[{ required: true, message: '请选择验车时间' }]}
              placeholder="请填写验车时间"
              allowClear
              style={styles.width300}
            />
          </Col>
          <Col span={24}>
            <FormInput
              name="remark"
              label="备注"
              maxLength={200}
              placeholder="请填写绑车备注信息，不超过200个字符"
              allowClear
              style={styles.width600}
            />
          </Col>
          <Col span={24}>
            <Form.Item
              label="验车清单上传"
              name="contractAttachmentList"
              rules={[{ required: true, message: '请上传验车清单' }]}
            >
               <Upload {...uploadPropNew}>
                    {newFileList?.length >= 5 ? null : <Button>添加清单</Button>}
                </Upload>
              <p style={{ margin: '15px 0 0 0' }}>
                清单说明：附件最大支持200M，
              </p>
              <p>支持格式：PDF、Word、Excel、JPG、PNG</p>
            </Form.Item>
          </Col>
        </Row>
        <p className={cardStyles.title}>合同信息</p>
        <Row gutter={24} className={cardStyles.rows}>
          <Col span={24}>
            <FormInput
              name="contractRemark"
              label="备注"
              maxLength={200}
              placeholder="请填写绑车备注信息，不超过200个字符"
              allowClear
              style={styles.width600}
            />
          </Col>
          <Col span={24}>
            <Form.Item
              label="合同附件上传"
              name="uoloadAttachmentList"
              rules={[{ required: true, message: '请上传合同附件' }]}
            >
              <Upload {...uploadPropContract}>
                    {contractFileList?.length >= 5 ? null : <Button>添加清单</Button>}
                </Upload>
              <p style={{ margin: '15px 0 0 0' }}>
                清单说明：附件最大支持30M，
              </p>
              <p>支持格式：PDF、Word、Excel、JPG、PNG</p>
            </Form.Item>
          </Col>
        </Row>
        <p className={cardStyles.title}>新车交车信息</p>
        <Row gutter={24} className={cardStyles.rows}>
          <Col span={24}>
            <FormTime
              name="deliveryTime"
              subtype="date"
              label="交车时间"
              rules={[{ required: true, message: '请选择交车时间' }]}
              placeholder="请选择交车时间"
              allowClear
              style={styles.width300}
            />
          </Col>
          <Col span={24}>
            <FormSelect
              name="deliveryPerson"
              label="交车工作人员"
              rules={[{ required: true, message: '请选择交车工作人员' }]}
              placeholder="请选择交车工作人员"
              allowClear
              style={styles.width300}
              items={workerList}
              keys='id'
              title='name'
            />
          </Col>
          <Col span={24}>
            <FormInput
              name="newRemark"
              label="备注"
              maxLength={200}
              placeholder="请填写绑车备注信息，不超过200个字符"
              allowClear
              style={styles.width600}
            />
          </Col>
          <Col span={24}>
            <Form.Item
              label="交车附件"
              name="closureAttachmentList"
              rules={[{ required: true, message: '请上传交车附件' }]}
            >
             <Upload {...uploadPropNewEnclosure}>
                    {newEnclosureFileList?.length >= 5 ? null : <Button>添加清单</Button>}
                </Upload>
              <p style={{ margin: '15px 0 0 0' }}>
                清单说明：附件最大支持30M，
              </p>
              <p>支持格式：PDF、Word、Excel、JPG、PNG</p>
            </Form.Item>
          </Col>
        </Row>
        <Row justify="center" style={{ marginTop: '20px' }}>
          <Form.Item>
            <Space>
              <Button shape="round" onClick={chanle}>取消</Button>
              <Button shape="round" type="primary" htmlType="submit" loading={loading}>
                提交
              </Button>
            </Space>
          </Form.Item>
        </Row>
      </Form>
    </div>
  );
}
export default connect(({ order: { details }, global }: any) => ({
  orderId: details.id,
  global,
}))(ExchangeCar);
